package com.study.service.impl;

import com.study.dao.RoleDao;
import com.study.dao.UserRoleDao;
import com.study.dao.RolePermissionDao;
import com.study.entity.Role;
import com.study.entity.RolePermission;
import com.study.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleDao roleDao;

    @Autowired
    private UserRoleDao userRoleDao;

    @Autowired
    private RolePermissionDao rolePermissionDao;

    @Override
    public int addRole(Role role) {
        return roleDao.insertRole(role);
    }

    /**
     * 删除角色信息，角色信息表roleInfo 的roleId是 关联表 角色权限表privilege 的外键
     * 需要先删除关联表中的外键引用
     */
    @Override
    public int deleteRole(Integer roleId) {
        // 删除用户权限表关联信息
        userRoleDao.deleteByRoleId(roleId);
        // 删除角色资源表关联数据
        rolePermissionDao.deleteByRoleId(roleId);

        return roleDao.deleteRole(roleId);
    }

    @Override
    public int modifyRole(Role role) {
        return roleDao.updateRole(role);
    }

    @Override
    public List<Role> selectAllRole() {
        return roleDao.selectAllRole();
    }

    // Save the assigned role

    /**
     * 保存用户分配的角色权限
     * @param userId
     * @param roleIdBatches
     */
    @Override
    public void saveAssignedRole(Integer userId, String[] roleIdBatches) {
        userRoleDao.deleteByUserId(userId);
        userRoleDao.batchInsert(userId,roleIdBatches);
    }

    @Override
    public Role selectRolePermission(Integer roleId) {
        return roleDao.selectRolePermission(roleId);
    }

    /**
     * 给用户分配角色
     * 删除角色权限表已有数据，再重新插入
     */
    @Override
    public void saveAllocatedPermission(Integer roleId, String[] resIdBatches) {
        // 删除roleId的所有资源
        rolePermissionDao.deleteByRoleId(roleId);
        // 保存最新的分配的资源
        rolePermissionDao.batchInsert(roleId, resIdBatches);
    }
}
